<?php
namespace app\api\controller\callback;

use app\common\system\logic\UserRoleLogic;
use app\common\system\model\User;
use app\common\third\Wechat as ThirdWechat;
use Firebase\JWT\JWT;
use think\Request;

class Wechat
{
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function qrlogin()
    {
        $post = $this->request->post();
        if (empty($post['code'])) return error([], "缺少code参数");
        $wechatLogic = new ThirdWechat();
        $result = $wechatLogic->get_user_info($post['code']);
        if($result['errcode'] != 0) return error([], $result['errmsg'], $result['errcode']);

        $model = new User();
        $user = $model->where('work_wechat', $result['UserId'])->find();
        if (empty($user)) return error([], "用户不存在或尚未绑定微信");

        $ini = config();
        $key = $ini['app']['jwt'];
        $token = JWT::encode($user->getData(), $key, 'HS256');
        $result['token'] = $token;
        $result['user'] = $user;

        // 获取用户的功能节点
        $userRoleLogic = new UserRoleLogic();
        $roles = $userRoleLogic->getUserRole($user['id'], false);
        $result['roles'] = array_column($roles, 'title');

        return success($result, "获取微信授权成功");
    }
}